package www.sofn.com.security.filter;


import cn.hutool.core.util.ObjectUtil;
import jakarta.annotation.Resource;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import www.sofn.com.security.domain.vo.TokenInfoVO;
import www.sofn.com.utils.SecurityUtils;
import www.sofn.com.security.service.TokenService;
import org.springframework.security.core.authority.SimpleGrantedAuthority;

import java.io.IOException;
import java.util.stream.Collectors;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    private TokenService tokenService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        final TokenInfoVO tokenInfo = tokenService.getTokenInfo(request);
        if (ObjectUtil.isNotNull(tokenInfo) && ObjectUtil.isNull(SecurityUtils.getAuthentication()))
        {
            tokenService.verifyToken(tokenInfo);
            UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(
                    tokenInfo.getUsername(), null, tokenInfo.getAuthorities().stream().map(SimpleGrantedAuthority::new).collect(Collectors.toList())
                    );
            authenticationToken.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
            SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        }
        filterChain.doFilter(request, response);
    }


}
